package com.atguigu.tingshu.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private KafkaService kafkaService;

    @Override
    public BigDecimal getTrackBreakSecond(Long userId, Long trackId) {
        String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
        Query query = Query.query(Criteria.where("userId").is(userId).and("trackId").is(trackId));
        UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
        return userListenProcess == null ? new BigDecimal("0") : userListenProcess.getBreakSecond();
    }

    @Override
    public void updateListenProcess(Long userId, UserListenProcessVo userListenProcessVo) {
        //查询mongodb
        String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
        Query query = Query.query(Criteria.where("userId").is(userId).and("trackId").is(userListenProcessVo.getTrackId()));
        UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
        //判断数据是否查到，如果没有则表示这是第一次记录
        if (userListenProcess == null) {
            userListenProcess = new UserListenProcess();
            BeanUtils.copyProperties(userListenProcessVo, userListenProcess);
            userListenProcess.setUserId(userId);
            //	设置是否显示
            userListenProcess.setIsShow(1);
            userListenProcess.setCreateTime(new Date());
            userListenProcess.setUpdateTime(new Date());
        } else {
            userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
            userListenProcess.setUpdateTime(new Date());
        }
        mongoTemplate.save(userListenProcess, collectionName);
        // 统计声音的播放数据   在同一天同一个用户同一个声音，只记录一次记录
        String key = userId + ":" + userListenProcessVo.getTrackId();
        //如果能过加锁就说明用户在最近的一条内没有播放该声音，向消息队列里发送消息统计声音数据
        if (stringRedisTemplate.opsForValue().setIfAbsent(key, userId.toString(), 24, TimeUnit.HOURS)) {
            TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
            trackStatMqVo.setTrackId(userListenProcessVo.getTrackId());
            trackStatMqVo.setCount(1);
            trackStatMqVo.setAlbumId(userListenProcessVo.getAlbumId());
            trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
            //业务编号,防止消息被重复消费
            trackStatMqVo.setBusinessNo(UUID.randomUUID().toString().replaceAll("-", ""));
            kafkaService.sendMessage(JSON.toJSONString(trackStatMqVo), KafkaConstant.QUEUE_TRACK_STAT_UPDATE);
        }
    }

    @Override
    public Map<String, Object> getLatelyTrack(Long userId) {
        //构造查询条件，通过userid查询用户的播放记录
        Query query = Query.query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Direction.DESC, "updateTime"));
        UserListenProcess userListenProcess = this.mongoTemplate.findOne(query, UserListenProcess.class
                , MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId));
        if(null == userListenProcess) {
            return null;
        }
        // 声明一个map 集合
        Map<String, Object> map = new HashMap<>();
        // 存储数据
        map.put("albumId", userListenProcess.getAlbumId());
        map.put("trackId", userListenProcess.getTrackId());
        // 返回数据
        return map;
    }
}
